package com.ayoldi.podcastusbsync.synchronizer;

import java.io.File;
import java.util.Iterator;

import javax.swing.filechooser.FileSystemView;


import org.apache.log4j.Logger;

public class USBDeviceCheckerThread extends Thread{

	static Logger LOG = Logger.getLogger(USBDeviceCheckerThread.class);
	
	private String deviceLabel;
	private String deviceFolder;
	long pollingUSBInterval;
	
	private USBDeviceSynchronizer usbDeviceSynchronizer;	
	
	private boolean stopped=false;

	public boolean isStopped() {
		return stopped;
	}

	public void setStopped(boolean stopped) {
		this.stopped = stopped;
	}

	public USBDeviceCheckerThread(USBDeviceSynchronizer synchronizer,long pollingUSBInterval){
		this.deviceLabel=synchronizer.deviceConfiguration.getDeviceLabel();
		this.deviceFolder=synchronizer.deviceConfiguration.getDeviceFolder();
		this.usbDeviceSynchronizer=synchronizer;
		this.pollingUSBInterval=pollingUSBInterval;
	}
	
	public void run() {
		LOG.info("Starting USB device checker thread for device: "+deviceLabel);
		while (deviceLabel!=null && deviceFolder!=null && deviceLabel.length()>0 && deviceFolder.length()>0){			
			if (stopped){
				break;
			}
			try {
				File[] roots=File.listRoots();
				if (roots!=null){
					for (File currentDrive : roots){
						LOG.debug("Device found on system: "+FileSystemView.getFileSystemView().getSystemDisplayName (currentDrive));
						String volumeLabel = USBDeviceSynchronizerUtils.getVolumeLabel(currentDrive);
						File absolutePodcastPath=new File(currentDrive, deviceFolder);
						if (volumeLabel!=null && volumeLabel.equalsIgnoreCase(deviceLabel) && currentDrive.canWrite() && absolutePodcastPath.exists()){
							LOG.info("Target device found: "+volumeLabel+". Synchronizing...");
							usbDeviceSynchronizer.sync(absolutePodcastPath);
							continue;
						}
					}
					
					
				}			
				
				// SI NO SE ENCUENTRA POR USB STORAGE MIRAMOS EN MTP
				// POR DEVICE NAME
				String deviceId=USBDeviceSynchronizerUtils.searchOnMTPDevicesByDeviceName(deviceLabel);
				// Y SINO POR FILENAME
				if (deviceId==null){
					deviceId=USBDeviceSynchronizerUtils.searchOnMTPDevicesByFilename(deviceLabel);
				}
				
				if (deviceId!=null){
					usbDeviceSynchronizer.syncMTP(deviceFolder,deviceId);
				}
			}
			catch (Exception e){
				continue;
			}
			if (stopped){
				break;
			}
			synchronized(this) {
                try {
                    this.wait(pollingUSBInterval);  
                }
                catch(InterruptedException ie){}
            }
			
			
		}
	
	}
	

	
	
}
